<template>
    <el-form
            ref="ruleForm"
            :inline="true"
            :model="datas"
            :rules="rules"
            label-width="130px"
            size="small"
    >
        <el-row>

            <el-col :span="8">
                <el-form-item label="代理名称" prop="agentName" style="width: 100%">
                    <el-autocomplete
                            v-model="datas.agentName"
                            style="width: 100%"
                            placeholder="请输入代理商名称"
                            @blur="agentBlur"
                            :fetch-suggestions="querySearchAsyncAgent"
                            @select="handleSelectAgent"
                    >
                        <template #default="{ item }">
                            <div class="distributeName" v-if="item.agentType == 'agent'">{{ item.agentName }}</div>
                            <div class="distributeName" v-else>{{ item.userName }}</div>
                        </template>
                    </el-autocomplete>

                </el-form-item>
            </el-col>

            <el-col :span="8">

                <el-form-item label="未找到代理商"  v-if="isNot" style="width: 100%">
                    <el-button type="text" @click="onCreate">创建代理商</el-button>
                </el-form-item>

            </el-col>

            <el-col :span="8">
                <el-form-item label="通用名" prop="productPopularName" style="width: 100%">
                    <product-popover
                            type="1"
                            :searchs="datas.productPopularName"
                            :disabled="dialogVisible || list.length > 0"
                            @confirm="productConfirm"
                    >
                        <el-input
                                :disabled="list.length > 0"
                                v-model="datas.productPopularName"
                                placeholder="请输入产品名称"
                        />
                    </product-popover>
                </el-form-item>
            </el-col>

            <el-col :span="8">
                <el-form-item label="商品名" style="width: 100%">

                    <el-input
                            v-model="datas.productName"
                            placeholder="商品名"
                            disabled=""
                    />
                </el-form-item>
            </el-col>

            <el-col :span="8">
                <el-form-item label="包装规格" style="width: 100%">
                    <el-input
                            v-model="datas.packSpecs"
                            placeholder="包装规格"
                            disabled=""
                    />
                </el-form-item>
            </el-col>

            <el-col :span="8">
                <el-form-item label="生产厂家" style="width: 100%">
                    <el-input
                            v-model="datas.producer"
                            placeholder="生产厂家"
                            disabled
                    />
                </el-form-item>
            </el-col>

            <el-col :span="8">
                <el-form-item label="代理地区" prop="areas" style="width: 100%">
                    <el-cascader
                            :disabled="list.length > 0"
                            style="width: 100%"
                            ref="cascader"
                            v-model="datas.areas"
                            :popper-append-to-body="false"
                            :options="citys"
                            :props="props1"
                            placeholder="请选择地区"
                            collapse-tags
                            clearable
                            @change="areaChange"
                    />
                </el-form-item>
            </el-col>

            <el-col :span="8">
                <el-form-item label="可营销终端" prop="terminalType" style="width: 100%">
                    <el-select v-model="datas.terminalType" placeholder="请选择营销终端" @change="terminalChange" :disabled="list.length > 0" style="width: 100%">
                        <el-option
                                v-for="item in appOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        />
                    </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="8">
                <el-form-item label="交易价" prop="tradePrice" style="width: 100%">

                    <div>
                        <price-input
                                style="width: 100%"
                                v-model:data="datas.tradePrice"
                                placeholder="请输入交易价"
                                is-unit
                                @blur="onBlur"
                                :unit-str="datas.sellUnit ? '元/' + getLabel('sell_unit',datas.sellUnit) : ''"
                        />
                        <template v-if="isUnde">
                            <div>
                                <span style="color: #E6A23C">输入的交易价低于该地区产品底价{{guidingPrice}}元/{{getLabel('sell_unit',datas.sellUnit)}}</span>
                            </div>

                        </template>

                    </div>

                </el-form-item>
            </el-col>

            <el-col :span="8">
                <el-form-item label="负责营销职员" prop="headId" style="width: 100%">
                    <el-select v-model="datas.headId" placeholder="请选择营销职员" :disabled="list.length > 0" @change="headChange" style="width: 100%">
                        <el-option
                                v-for="item in headOptions"
                                :key="item.id"
                                :label="item.realName"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="8">
                <el-form-item style="width: 100%" label="代理期限至" prop="agentEndTime">
                    <date-picker
                            style="width: 100%"
                            v-model:date="datas.agentEndTime"
                            :disabled-date="disabledDate"
                            placeholder="请选择代理期限"
                    />
                </el-form-item>
            </el-col>

            <el-col :span="8">
                <el-form-item label="最低销量" style="width: 100%">
                    <el-input
                            v-model.number="datas.minSale"
                            placeholder="请输入最低销量"
                    >
                        <template #append>
                  <span
                          v-if="datas.sellUnit"
                          style="margin-right: 10px"
                  >{{ getLabel('sell_unit',datas.sellUnit) }}/</span>
                            <el-select
                                    v-model="datas.minSaleUnit"
                                    placeholder=""
                                    style="width: 80px"
                            >
                                <el-option
                                        v-for="item in unitOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                />
                            </el-select>
                        </template>
                    </el-input>

                </el-form-item>

            </el-col>

            <el-col :span="8">
                <el-form-item label="销量保证金" style="width: 100%">
                    <el-input
                            v-model.number="datas.minSalePromise"
                            placeholder="请输入销量保证金"
                            clearable
                    >
                        <template #append>
                            <span>元</span>
                        </template>
                    </el-input>

                </el-form-item>
            </el-col>

            <el-col :span="24">
                <el-form-item label="其他约定" prop="remark" style="width: 100%">
                    <el-input
                            v-model="datas.remark"
                            placeholder="请输入其他约定"
                            clearable
                    />
                </el-form-item>
            </el-col>
        </el-row>

    </el-form>

    <fromDialog ref="fromDialog"/>
</template>

<script>
    import { useRoute } from 'vue-router'
    import {getServeAreaData2} from "../../../../../../../../utils/areaFuc";
    import {crmStore} from "../../../../../../store";
    import {defineAsyncComponent, defineComponent, getCurrentInstance, inject, reactive, ref, toRefs, onMounted} from 'vue'

    export default defineComponent({
        name: "informationView",
        components:{
            fromDialog : defineAsyncComponent(
                () => import('../../../../customer/modules/fromDialog.vue')
            ),
        },
        props:{
            datas:{
                type:Object,
                default:{}
            },
            list:{
                type:Array,
                default:[]
            }
        },
        setup(props,{emit}){
            const validatePrice = async(rule, value, callback) => {
                if (value === '') {
                    callback('请输入交易价')
                } else {
                    if ( value == 0){
                        callback('请输入交易价')
                    }else{
                        callback()
                    }

                }
            }
            const route = useRoute()
            const currentInstance = getCurrentInstance()
            const rules = ref({
                productPopularName: [
                    {
                        required: true,
                        message: '请选择产品',
                        trigger: 'blur',
                    },
                ],
                agentEndTime: [
                    {
                        type: 'date',
                        required: true,
                        message:'请选择代理期限至',
                        trigger: 'change',
                    },
                ],
                agentAttribute: [
                    {
                        required: true,
                        message: '请选择代理属性',
                        trigger: 'change',
                    },
                ],
                areas: [
                    {
                        required: true,
                        message: '请选择代理地区',
                        trigger: 'change',
                    },
                ],
                tradePrice: [
                    {
                        required: true,
                        validator:validatePrice,
                        trigger: 'blur',
                    },
                ],
                minSale: [
                    {
                        required: true,
                        message: '请输入最低销量',
                        trigger: 'blur',
                    },
                ],
                minSalePromise: [
                    {
                        required: true,
                        message: '请输入销量保证金',
                        trigger: 'blur',
                    },
                ],
                headId: [
                    {
                        required: true,
                        message: '请选择营销职员',
                        trigger: 'change',
                    },
                ],
                agentName: [
                    {
                        required: true,
                        message: '请选择代理商',
                        trigger: 'change',
                    },
                ],
                terminalType: [
                    {
                        required: true,
                        message: '请选择可营销终端',
                        trigger: 'change',
                    },
                ],
            })
            const api = inject('api')
            const props1 = reactive({multiple: true, expandTrigger: 'hover', label: 'regionName', value: 'regionCode',})
            const userInfo = crmStore.getters['user/userInfo']
            const appOptions = crmStore.getters['dictionary/getDictionary']['app_mode']
            const unitOptions = crmStore.getters['dictionary/getDictionary']['sell_num_unit']
            var data = reactive({
                isNot:false,
                dialogVisible:false,
                citys:[],
                cascader:null,
                ruleForm:null,
                fromDialog:null,
                headOptions:crmStore.getters['company/getHeadOptions'],
                isUnde:false,
                productPrices:[],
                guidingPrice:0,
            })

            // 获取代理商列表
            const querySearchAsyncAgent = async(queryString, cb) => {
                const a = {
                    keyWord: queryString,
                }
                let results = []
                const res = await api.editorial.EDITORIAL_KEYWORDS(a)
                if (!res.code && res.data) {
                    results = res.data.list || []
                    if ((!res.data.list || !res.data.list.length) && queryString){
                        data.isNot = true
                    }else {
                        data.isNot = false
                    }
                }
                cb(results)
            }

            const agentBlur = () => {
                if (!props.datas.agentId){
                    props.datas.agentName = ''
                }
            }

            // 代理商事件
            const handleSelectAgent = (val) => {
                props.datas.agentId = val.id
                props.datas.agentName = val.agentName
            }

            const onCreate = () => {
                // if (data.formData.radio == 'agent'){
                //     data.agentDialog.open(null)
                // }else {
                //     data.formPersonnelRef.open(null, 1)
                // }
                data.fromDialog.open()
            }

            const productConfirm = (val) => {
                props.datas.productId = val.id
                props.datas.productPopularName = val.productPopularName
                props.datas.productName = val.productName
                props.datas.approvalNumber = val.approvalNumber
                props.datas.packSpecs = val.packSpecs
                props.datas.producer = val.producer
                props.datas.sellUnit = val.sellUnit

                getArea()
                props.datas.areas = []
                props.datas.region = []

                getProductPrice()
            }

            const terminalChange = () => {
                getProductPrice()
            }

            const getArea = () => {
                if (props.datas.productId) {
                    const pam = {
                        productId: props.datas.productId,
                        agentAttribute: '2',
                    }
                    api.signedAgent.AGENT_PRODUCT_REGION(pam).then((res) => {
                        if (!res.code && res.data) {
                            data.citys = res.data.region
                        }
                    })
                        .catch()
                }
            }

            const areaChange = (val) => {
                const serve = getServeAreaData2(
                    val,
                    data.cascader.getCheckedNodes()
                )
                props.datas.region = serve
                console.log(props.datas.region)
                emit('change')
                getProductPrice()
            }

            const getProductPrice = () => {
                data.productPrices = []
                if (props.datas.region.length && props.datas.productId && props.datas.terminalType){
                    api.signedAgent.PRODUCT_PRICE_STRATEGY_MIN_PRICE({productId:props.datas.productId,region:props.datas.region,terminalType:props.datas.terminalType}).then(res=>{
                        if (!res.code){
                            data.productPrices = res.data.list || []
                            if (props.datas.tradePrice){
                                onBlur()
                            }
                        }else {
                            currentInstance.proxy.customMessage({type:'error',message:res.msg})
                        }
                    })
                }
            }

            const onBlur = () => {
                data.isUnde = false
                if (data.productPrices && data.productPrices.length && props.datas.tradePrice){
                    data.isUnde = true
                    for (let i = 0; i < data.productPrices.length; i++) {
                        data.guidingPrice = data.productPrices[i].guidingPrice
                        if (props.datas.tradePrice >= data.productPrices[i].guidingPrice){
                            data.isUnde = false
                            break
                        }
                    }
                }
            }

            const headChange = () => {
                const index = data.headOptions.findIndex(
                    (a) => a.id == props.datas.headId
                )
                if (index != -1) {
                    props.datas.headName = data.headOptions[index].realName
                }

            }

            const validata = () => {
                return new Promise((resolve, reject) => {
                    data.ruleForm.validate((value) => {
                        if (value) {
                            // if (props.datas.tradePrice >= )
                            resolve()
                        }else{
                            reject()
                        }
                    })
                })
            }

            const getTaskData = (id) => {
                data.dialogVisible = true
                api.task.TASK_CUSTOMER_DETAIL(id).then(res => {

                    if (!res.code){

                        props.datas.productId = res.data.productId
                        props.datas.productPopularName = res.data.productPopularName
                        props.datas.productName = res.data.productName
                        props.datas.packSpecs = res.data.packSpecs
                        props.datas.producer = res.data.producer
                        props.datas.sellUnit = res.data.sellUnit

                        props.datas.agentId = res.data.objectId
                        props.datas.agentName = res.data.objectName

                        getArea()
                        getProductPrice()
                    }else{
                        currentInstance.proxy.customMessage({type:'error',message:res.msg})
                    }

                    setTimeout(()=>{
                        data.dialogVisible = false
                    },500)
                }).catch(res=>{
                    data.dialogVisible = false
                })
            }

            onMounted(() => {
                props.datas.headId = userInfo.ID
                props.datas.headName = userInfo.realName
                if (route.query.taskId){
                    getTaskData(route.query.taskId)
                }
            })

            return{
                ...toRefs(data),
                rules,
                props1,
                appOptions,
                unitOptions,

                querySearchAsyncAgent,
                handleSelectAgent,
                onCreate,
                productConfirm,
                areaChange,
                headChange,
                validata,
                terminalChange,
                onBlur,
                agentBlur,
            }
        }
    })
</script>

<style scoped>

</style>
